#include <stdlib.h>
#include "table.h"

HashTable *create() {
    HashTable *table = NULL;
    size_t size = sizeof(Entry) * TABLE_DEFAULT_SIZE;
    table = malloc(sizeof(HashTable));
    table->nodes = malloc(size);
    for (int i = 0; i < TABLE_DEFAULT_SIZE; i++) {
        table->nodes[i] = NULL;  // 初始化
    }
    table->get = get;
    table->put = put;
    table->clear = clear;
    return table;
}

Entry *get(HashTable *ht, int key) {
    // 计算索引
    unsigned int index = hash(key);
    return ht->nodes[index];
}

unsigned int hash(int key) {
    unsigned int hash = 5381;
    hash += (hash << 5) + key;
    return (hash & 0x7FFFFFFF) % TABLE_DEFAULT_SIZE;
}


int put(HashTable *ht, int key, int val) {

    // 计算下标
    unsigned int index = hash(key);


    Entry *newNode = malloc(sizeof(Entry));
    newNode->key = key;
    newNode->val = val;
    newNode->next = NULL;

    if (ht->nodes[index] == NULL) {
        ht->nodes[index] = newNode;  // 无冲突
    } else {
        /**
         * 值一样，不操作
         */
        if (ht->nodes[index]->val == val) {
            free(newNode);
            newNode = NULL;
            return 0;
        }
        // 有冲突
        Entry *node = ht->nodes[index];
        while (node->next != NULL) {
            node = node->next;  // 迭代
        }
        node->next = newNode;  // 给链表赋值
    }
    return 1;
}

void clear(HashTable *ht) {
    if (ht != NULL) {
        for (int i = 0; i < TABLE_DEFAULT_SIZE; i++) {
            Entry *node = ht->nodes[i];
            if (node != NULL) {
                Entry *tmp = node;
                while (node->next != NULL) {
                    tmp = node->next;
                    free(node);
                    node = tmp;
                }
            }
        }
        free(ht->nodes);
        ht->nodes = NULL;
        ht->get = NULL;
        ht->put = NULL;
        ht->clear = NULL;
        free(ht);
        ht = NULL;
    }
}